<?php
    class Admin_Model_News extends Zend_Db_Table_Abstract
    {
        protected $_name = 'news';
        protected $_primary = 'news_id';
        protected $_db;
        protected $_fullToday;
        
        public function __construct()
        {
            $this->_db = Zend_Registry::get('db');
            $this->_fullToday = date('Y-m-d H:i:s');
        }
        
        public function getListId()
        {
            $sql = $this->_db->select()
                            ->from($this->_name, $this->_primary);
            $result = $this->_db->fetchAll($sql);
            return $result;
        }
        
        public function listNews()
        {
            $sql = $this->_db->select()
                            ->from($this->_name)
                            ->order('news_id DESC');
            $result = $this->_db->fetchAll($sql);
            return $result;
        }
        
        public function getNewsByIdForFile($news_id)
        {
            $news = array(
                'n.news_id',
                'n.news_title',
                'n.news_plaintext',
                'n.news_image',
                'n.type_image',
                'n.create_date',
                'n.status',
            );
            $category = array(
                'c.cat_id',
                'c.cat_name',
            );
            $sql = $this->_db->select()
                            ->from('news as n', $news)
                            ->joinLeft('category as c', 'c.cat_id = n.cat_id', $category)
                            ->where('news_id = ?', $news_id);
            $result = $this->_db->fetchRow($sql);
            return $result;
        }
        
        public function checkNews($news_title, $news_id = '')
        {
            if($news_id != '')
            {
                $sql = $this->_db->select()
                            ->from($this->_name)
                            ->where('news_title = ?', $news_title)
                            ->where('news_id = ?', $news_id);
                $result = $this->_db->fetchAll($sql);
                return count($result);
            }
            else
            {
                $sql = $this->_db->select()
                            ->from($this->_name)
                            ->where('news_title = ?', $news_title);
                $result = $this->_db->fetchAll($sql);
                return count($result);
            }
        }
        
        public function getNewsById($news_id)
        {
            $sql = $this->_db->select()
                            ->from($this->_name)
                            ->where('news_id = ?', $news_id);
            $result = $this->_db->fetchRow($sql);
            return $result;
        }
        
        public function addNews( $news_title, $news_image, $news_content, $news_plaintext)
        {
            $data = array(
                'news_title' => $news_title,
                'news_image' => $news_image,
                'news_content' => $news_content,
                'news_plaintext' => $news_plaintext,
                'status' => 0,
                'create_date' => $this->_fullToday,
            );
            $this->_db->insert($this->_name, $data);
            $news_id = $this->_db->lastInsertId($this->_name, 'news_id');
            return $news_id;
        }
        
        public function editNews($news_id, $news_title, $news_image = " ", $news_content, $news_plaintext, $status)
        {
            $where = $this->getAdapter()->quoteInto('news_id = ?', $news_id);
            if($news_image != "")
            {
                $data = array(
                    'news_title' => $news_title,
                    'news_image' => $news_image,
                    'news_content' => $news_content,
                    'news_plaintext' => $news_plaintext,
                    'status' => $status,
                );
                $result = $this->_db->update($this->_name, $data, $where);
                if($result)
                {
                    return true;
                }
                else
                {
                    return false;
                    
                }
            }
            else
            {
                $data = array(
                    'news_title' => $news_title,
                    'news_content' => $news_content,
                    'news_plaintext' => $news_plaintext,
                    'status' => $status,
                );
                $result = $this->_db->update($this->_name, $data, $where);
                if($result)
                {
                    return true;
                    
                }
                else
                {
                    return false;
                    
                }
            }
        }
        
        public function deleteNews($news_id)
        {
            $where = $this->getAdapter()->quoteInto('news_id = ?', $news_id);
			$query = $this->_db->select()
                            ->from($this->_name)
							->where($where);
			$row = $this->_db->fetchRow($query);
			if (is_file(PUBLIC_PATH . '/files/news/' . $row['news_image']))
			{
				unlink(PUBLIC_PATH . '/files/news/' . $row['news_image']);
			}
			$result = $this->_db->delete($this->_name, $where);
			$index = Zend_Search_Lucene::open('files/news');
            $hits = $index->find('news_id:' . $news_id);
                      
            foreach($hits as $hit)
            {
                $index->delete($hit->id);
            }
            $index->commit();
            $index->optimize();
        }
        
        public function deleteManyNews($listId)
        {
            $index = Zend_Search_Lucene::open('files/news');
            foreach ($listId as $value)
			{
                $where = $this->getAdapter()->quoteInto('news_id = ?', $value);
				$query = $this->_db->select()
							->from($this->_name)
							->where($where);
				$row = $this->_db->fetchRow($query);
				if (is_file(PUBLIC_PATH . '/files/news/' . $row['news_image']))
				{
					unlink(PUBLIC_PATH . '/files/news/' . $row['news_image']);
				}
				$this->_db->delete($this->_name, $where);
                $hits = $index->find('news_id:' . $value);
                foreach($hits as $hit)
                {
                    $index->delete($hit->id);
                }
			}
            $index->commit();
            $index->optimize();
        }
        
        public function searchNews($keyword)
        {
            Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
            setlocale(LC_CTYPE, 'UTF-8');
            Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
			$index = Zend_Search_Lucene::open('files/news');
            if(!empty($keyword))
            {
                $hits = $index->find($keyword);
                return $hits;
            }
        }
        
        public function saveAddItem($arrParam = null, $options = null)
        {
            if($options['task'] == 'add')
            {
                try
                {
                    Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
                    setlocale(LC_CTYPE, 'UTF-8');
                    Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
                    $index = Zend_Search_Lucene::open('files/news');
                    Zend_Search_Lucene::setResultSetLimit(350);
                }
                catch(exception $e)
                {
                    Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
                    setlocale(LC_CTYPE, 'UTF-8');
                    Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
                    $index = Zend_Search_Lucene::create('files/news');
                }
                
                $doc = new Zend_Search_Lucene_Document();
                $doc->addField(Zend_Search_Lucene_Field::keyword('news_id', $arrParam['news_id']))
                    ->addField(Zend_Search_Lucene_Field::text('news_title', $arrParam['news_title'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::text('news_title_filter', $arrParam['news_title_filter'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::text('news_plaintext', $arrParam['news_plaintext'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::text('news_plaintext_flter', $arrParam['news_plaintext_filter'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::unIndexed('news_image', $arrParam['news_image']))
                    ->addField(Zend_Search_Lucene_Field::unIndexed('type_image', $arrParam['type_image']))
                    ->addField(Zend_Search_Lucene_Field::unIndexed('create_date', $arrParam['create_date']))
                    ->addField(Zend_Search_Lucene_Field::keyword('status', $arrParam['status']));
                    
                $index->addDocument($doc);
                $index->commit();
                $index->optimize();
            }
            
            if($options['task'] == 'edit')
            {
                try
                {
                    Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
                    setlocale(LC_CTYPE, 'UTF-8');
                    Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
                    $index = Zend_Search_Lucene::open('files/news');
                    Zend_Search_Lucene::setResultSetLimit(350);
                }
                catch(exception $e)
                {
                    Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('UTF-8');
                    setlocale(LC_CTYPE, 'UTF-8');
                    Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());
                    $index = Zend_Search_Lucene::create('files/news');
                }
                
                $hits = $index->find('news_id:'.$arrParam['news_id']);
                foreach($hits as $hit)
                {
                    $index->delete($hit->id);
                }
                
                $doc = new Zend_Search_Lucene_Document();
                $doc->addField(Zend_Search_Lucene_Field::keyword('news_id', $arrParam['news_id']))
                    ->addField(Zend_Search_Lucene_Field::text('news_title', $arrParam['news_title'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::text('news_title_filter', $arrParam['news_title_filter'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::text('news_plaintext', $arrParam['news_plaintext'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::text('news_plaintext_flter', $arrParam['news_plaintext_filter'], 'UTF-8'))
                    ->addField(Zend_Search_Lucene_Field::unIndexed('news_image', $arrParam['news_image']))
                    ->addField(Zend_Search_Lucene_Field::unIndexed('create_date', $arrParam['create_date']))
                    ->addField(Zend_Search_Lucene_Field::keyword('status', $arrParam['status']));
                
                $index->addDocument($doc);
                $index->commit();
                $index->optimize();
            }
        }
        function truncateString($str, $len, $charset="UTF-8"){
        $str = html_entity_decode($str, ENT_QUOTES, $charset);   
        if(mb_strlen($str, $charset)> $len){
            $arr = explode(' ', $str);
            $str = mb_substr($str, 0, $len, $charset);
            $arrRes = explode(' ', $str);
            $last = $arr[count($arrRes)-1];
            unset($arr);
            if(strcasecmp($arrRes[count($arrRes)-1], $last))   unset($arrRes[count($arrRes)-1]);
          return implode(' ', $arrRes)."...";   
       }
        return $str;
        }


    }
